package gsw.tool.json.serializer;

import gsw.tool.json.FieldInfo;
import gsw.tool.json.JsonConfig;
import gsw.tool.json.Utils;

/**
 * 属性序列化器
 */
public class FieldSerializer {

    private final FieldInfo fieldInfo;
    private final String key;
    private final boolean isPrimitive;//是否是基本数据类型或者它的包装类

    public FieldSerializer(FieldInfo fieldInfo) {
        this.fieldInfo = fieldInfo;
        this.key = '"' + fieldInfo.name + "\":";
        //value的类型
        Class type = fieldInfo.type;
        isPrimitive = type.isPrimitive() || Utils.isBox(type);
    }

    /**
     * 序列化属性
     */
    public String serializer(JsonConfig config, Object object) {
        Object o = fieldInfo.get(object);
        //属性没有值
        if (null == o) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        if (isPrimitive) {//基本类型
            sb.append(key);
            sb.append(o);
        } else if (Utils.isString(fieldInfo.type)) {//string类型
            sb.append(key);
            sb.append("\"");
            sb.append(o);
            sb.append("\"");
        } else {//JavaBean或List类型
            ObjectSerializer serializer = config.getSerializer(fieldInfo.type);
            sb.append(key);
            serializer.serializer(config, sb, o);
        }
        return sb.toString();
    }
}
